package com.wsoft.system.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsoft.constant.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.annotation.InitRedisCache;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.RedisService;
import com.wsoft.system.dto.TsConfigInfoDto;
import com.wsoft.system.entity.TsConfigInfoEntity;
import com.wsoft.system.mapper.TsConfigInfoMapper;
import com.wsoft.system.service.ITsConfigInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 个人配置系统信息表 服务实现类
 * </p>
 *
 * @author kyle
 * @since 2024年09月01日 08:52:31
 */
@Service
public class TsConfigInfoServiceImpl extends ServiceImpl<TsConfigInfoMapper, TsConfigInfoEntity> implements ITsConfigInfoService {

    @Resource
    private RedisService redisService;
    @Override
    public boolean insert(TsConfigInfoDto dto) {
        TsConfigInfoEntity entity = Convert.convert(TsConfigInfoEntity.class, dto);
        //校验用户、组织是否重复
        QueryWrapper<TsConfigInfoEntity> query = new QueryWrapper<>();
        query.lambda().eq(TsConfigInfoEntity::getOrgId,entity.getOrgId())
                .or().eq(TsConfigInfoEntity::getMemberId,entity.getMemberId());
        List<TsConfigInfoEntity> list = list(query);
        if (list.size()>0){
            Asserts.fail("[ts.configInfo.exist]");
        }
        return save(entity);
    }

    @Override
    public boolean update(TsConfigInfoDto dto) {
        TsConfigInfoEntity entity = Convert.convert(TsConfigInfoEntity.class, dto);
        if (entity.getMemberId()!=null){
            redisService.del(RedisKeyConstant.CONFIG_INFO_MEMBER+entity.getMemberId());
        }
        if (entity.getOrgId()!=null){
            redisService.del(RedisKeyConstant.CONFIG_INFO_ORG+entity.getOrgId());
        }
        return updateById(entity);
    }

    @Override
    @InitRedisCache( type = RedisKeyConstant.CONFIG_INFO+"*",
            value = RedisKeyConstant.REDIS_PATTERN)
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public TsConfigInfoEntity getConfigInfo(Long id) {
        return getById(id);
    }

    @Override
    @GetRedisCache( type = RedisKeyConstant.CONFIG_INFO_ORG,
            value = RedisKeyConstant.REDIS_SELF)
    public TsConfigInfoEntity getConfigInfoByOrg(Long orgId) {
        QueryWrapper<TsConfigInfoEntity> query = new QueryWrapper<>();
            query.lambda().eq(TsConfigInfoEntity::getOrgId,orgId);
        return getOne(query);
    }
}
